package db

import (
	"github.com/go-xorm/xorm"
	"until/yml"
	_ "github.com/go-sql-driver/mysql"
	"time"
	"github.com/go-xorm/core"
	"github.com/jmoiron/sqlx"
	"fmt"
	"until/logger"
)

type Status int8
const (
	Disabled Status = 0 // 禁用
	Failure  Status = 0 // 失败
	Enabled  Status = 1 // 启用
	Running  Status = 1 // 运行中
	Finish   Status = 2 // 完成
	Cancel   Status = 3 // 取消
)

const (
	Page        = 1      // 当前页数
	PageSize    = 20     // 每页多少条数据
	MaxPageSize = 10000 // 每次最多取多少条
)

const DefaultTimeFormat = "2006-01-02 15:04:05"
var TablePrefix string
var Db_Orm *xorm.Engine
var Db_Sqlx *sqlx.DB
func SetOrm() {
	engine, err := xorm.NewEngine("mysql", yml.Config.Mysql)
	if err!=nil {
		logger.Error(err)
		panic(err.Error())
	}
	if ""!=yml.Config.MysqlPrefix{
		tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, yml.Config.MysqlPrefix)
		TablePrefix=yml.Config.MysqlPrefix
		engine.SetTableMapper(tbMapper)
	}
	go func() {
		pingt:=180
		if yml.Config.MysqlPing!=0 {
			pingt=yml.Config.MysqlPing
		}
		ticker := time.NewTicker(time.Second*time.Duration(pingt))
		for _ = range ticker.C {
			engine.Ping()
		}
	}()
	Db_Orm=engine

}
func SetSqlx()  {
	db, err := sqlx.Open("mysql",yml.Config.Mysql)
	if err != nil {
		fmt.Println("Open error:", err)
		panic(err)
	}
	Db_Sqlx=db
	go func() {
		pingt:=20
		if yml.Config.MysqlPing!=0 {
			pingt=yml.Config.MysqlPing
		}
		ticker := time.NewTicker(time.Second*time.Duration(pingt))
		for _ = range ticker.C {
			Db_Sqlx.Ping()
		}
	}()


}
//闭包十五处理
func DoSession(f func(s *xorm.Session))  {
	session := Db_Orm.NewSession()
	defer session.Close()
	f(session)
}
